package com.hfzy.ihk.web.oauth.client.filter;


import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;

import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by YANFA on 2019/2/22.
 */
@Component("ajaxSessionOutFilter")
public class AjaxSessionOutFilter extends GenericFilterBean  {


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        javax.servlet.http.HttpServletRequest req = (javax.servlet.http.HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String header = req.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equals(header) ? true : false;
        try {
            String url = ((HttpServletRequest) request).getRequestURI();
            if(url.contains("gatewayCardSlot")||url.contains("external")) { //这里特殊处理一下被置业系统包裹的页面链接,如果需要给置业或者外部直接调用的在前缀加个external
                isAjax = false;
            }
            if(isAjax) {
                Object SPRING_SECURITY_CONTEXT = ((HttpServletRequest) request).getSession().getAttribute("SPRING_SECURITY_CONTEXT");
                if(SPRING_SECURITY_CONTEXT==null){ //说明ajax请求超时了
                    response.getWriter().print("timeout");  //设置超时标识
//                    response.getWriter().print("alert(1)");
                    response.getWriter().close();
                }else{
                    chain.doFilter(request,response);
                }
            }else{
                chain.doFilter(request,response);
            }

        } catch (IOException e) {
            logger.error("异常：",e);
        }



    }


}
